package ro.unibuc.nautilus.controllers;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import ro.unibuc.nautilus.controllers.editors.DatePropertyEditor;
import ro.unibuc.nautilus.controllers.editors.ShipPropertyEditor;
import ro.unibuc.nautilus.domain.Employee;
import ro.unibuc.nautilus.domain.Ship;
import ro.unibuc.nautilus.service.EmployeesService;
import ro.unibuc.nautilus.service.ShipsService;

public class EditEmployeeController extends SimpleFormController {
	private ShipsService shipsService;
	private EmployeesService employeesService;

	public EditEmployeeController() {
	}

	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) {

		ShipPropertyEditor hpe = new ShipPropertyEditor();
		hpe.setShipsService(shipsService);

		binder.registerCustomEditor(Ship.class, hpe);
		binder.registerCustomEditor(Date.class, new DatePropertyEditor());
	}

	@Override
	protected Map referenceData(HttpServletRequest request) throws Exception {
		Map model = new HashMap();

		model.put("ships", shipsService.findAll());
		return model;
	}

	@Override
	protected ModelAndView onSubmit(Object command) throws Exception {
		Employee employee = (Employee) command;
		employeesService.createOrUpdate(employee);
		return new ModelAndView(getSuccessView());
	}

	@Required
	public void setShipsService(ShipsService shipsService) {
		this.shipsService = shipsService;
	}

	@Required
	public void setEmployeesService(EmployeesService employeesService) {
		this.employeesService = employeesService;
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		long employeeId = ServletRequestUtils.getLongParameter(request,
				"employeeId", -1);

		// Assume create new if argument is missing
		if (employeeId == -1) {
			return new Employee();
		}

		return employeesService.findEmployee(employeeId);
	}
}
